<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manager/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/manager/shop">商店信息</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="body_box">
      <el-card style="max-width: 700px">
        <template #header>
          <div class="card-header">
            <span>商家信息</span>
          </div>
        </template>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="商店名称">
            <el-input v-model="ruleForm.shopName" />
          </el-form-item>

          <el-form-item label="营业时间">
            <div class="example-basic">
              <el-time-picker
                v-model="ruleForm.businessStartTime"
                placeholder="营业开始时间"
              />
              <el-time-picker
                v-model="ruleForm.businessEndTime"
                arrow-control
                placeholder="营业结束时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="营业状态">
            <el-select-v2
              v-model="ruleForm.businessState"
              placeholder="Activity count"
              :options="options"
            />
          </el-form-item>

          <el-form-item label="图片">
            <el-upload
              v-model:file-list="fileList"
              action="/api/upload/img"
              :headers="tokenBody"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="hanleSuccess"
              limit="1"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商店介绍">
            <el-input v-model="ruleForm.shopIntroduce" type="textarea" />
          </el-form-item>
          <el-form-item style="display: flex; justify-content: end; width: 100%">
            <el-button type="primary" @click="submitForm(ruleFormRef)"> 修改 </el-button>
          </el-form-item>
        </el-form>

        <template #footer>Have a good day~</template>
      </el-card>
    </div>

    <el-dialog v-model="photoShowFlag">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import type { UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
const fileList = ref<UploadUserFile[]>([]);
const dialogVisible = ref(false);
const token = ref(localStorage.getItem("shop_auth_token"));
const tokenBody = ref({
  token: token.value,
});

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles);
};

const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  const url = res.message;
  fileList.value = [];
  fileList.value.push({
    name: "hhe",
    url: res.message,
  });
  // console.log(JSON.stringify(ruleForm.shopImg));
};

const dialogFormVisible = ref(false);
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

const ruleForm = reactive({
  shopId: "",
  shopName: "",
  shopIntroduce: "",
  shopImg: "",
  shopState: 1,
  businessState: 1,
  businessStartTime: "",
  businessEndTime: "",
});

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log("submit!");

      let req = {
        shopId: sth.value.shopId,
        shopName: ruleForm.shopName,
        shopAddress: ruleForm.shopAddress,
        shopMasterId: sth.value.shopMasterId,
        shopIntroduce: ruleForm.shopIntroduce,
        shopImg: fileList.value[0].url,
        shopState: sth.value.shopState,
        inputTime: sth.value.inputTime,
        businessState: ruleForm.businessState,
        businessStartTime: formatDate(ruleForm.businessStartTime),
        businessEndTime: formatDate(ruleForm.businessEndTime),
      };
      if (fileList.value == null || fileList.value.length == 0) {
        req = {
          shopId: sth.value.shopId,
          shopName: ruleForm.shopName,
          shopAddress: ruleForm.shopAddress,
          shopMasterId: sth.value.shopMasterId,
          shopIntroduce: ruleForm.shopIntroduce,
          shopState: sth.value.shopState,
          inputTime: sth.value.inputTime,
          businessState: ruleForm.businessState,
          businessStartTime: formatDate(ruleForm.businessStartTime),
          businessEndTime: formatDate(ruleForm.businessEndTime),
        };
      }
      console.log(req);

      axios
        .post("/api/shop/update", req, {
          headers: {
            token: token.value,
          },
        })
        .then((res) => {
          console.log(res);
          getSaleDate();
          ElMessage({
            type: "success",
            message: "更新信息成功",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const formatDate = (date) => {
  // 使用 Date 对象来解析日期字符串

  var hours = date.getHours().toString().padStart(2, "0");
  var minutes = date.getMinutes().toString().padStart(2, "0");
  var seconds = date.getSeconds().toString().padStart(2, "0");

  return `${hours}:${minutes}:${seconds}`;
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = [
  {
    value: 1,
    label: "营业",
  },
  {
    value: 2,
    label: "休业",
  },
];
const sth = ref("");

const formatDateFromBack = (timeStringFromBackend) => {
  // 获取当前日期
  var currentDate = new Date();

  // 使用给定时间字符串创建一个日期对象
  var parsedDate = new Date(
    currentDate.getFullYear(),
    currentDate.getMonth(),
    currentDate.getDate(),
    parseInt(timeStringFromBackend.split(":")[0]),
    parseInt(timeStringFromBackend.split(":")[1])
  );

  // console.log(parsedDate); // 输出当前日期加上给定时间的完整日期对象
  return parsedDate;
};

const getSaleDate = () => {
  axios
    .get("/api/shop/info", {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      // console.log(res);
      const msg = res.data.message;
      if (msg.shopAddress) ruleForm.shopAddress = msg.shopAddress;
      ruleForm.shopId = msg.shopId;
      ruleForm.shopName = msg.shopName;
      ruleForm.businessEndTime = msg.businessEndTime
        ? formatDateFromBack(msg.businessEndTime)
        : "";
      ruleForm.businessStartTime = msg.businessStartTime
        ? formatDateFromBack(msg.businessStartTime)
        : "";
      if (msg.shopIntroduce) ruleForm.shopIntroduce = msg.shopIntroduce;
      if (msg.businessState) ruleForm.businessState = msg.businessState;
      if (msg.shopImg != null) {
        fileList.value = [];
        fileList.value.push({
          name: "hhe",
          url: msg.shopImg,
        });
        console.log(msg.shopImg);
      }
      sth.value = res.data.message;
    })
    .catch((err) => {
      console.log(err);
    });
};
getSaleDate();
</script>

<style lang="scss" scoped>
.body_box {
  margin-top: 5vh;
  margin-left: 5vw;
}
.header {
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.insert {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
